package com.bawei.module_mall.ui.search

import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.View
import android.view.inputmethod.InputMethodManager
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.lib_mvi.Router
import com.bawei.lib_mvi.base.BaseMVIActivity
import com.bawei.module_mall.R
import com.bawei.module_mall.adapter.GoodsAdapter
import com.bawei.module_mall.databinding.ActivityGoodsSearchBinding
import com.bawei.module_mall.http.intent.ShopIntent
import com.bawei.module_mall.http.state.ShopState
import com.bawei.module_mall.http.viewModel.ShopViewModel
import com.bawei.module_mall.model.RequestSearchGoodsModel
import com.bawei.module_mall.model.SearchGoodsModelItem
import kotlinx.coroutines.launch

@Route(path = "/mall/GoodsSearchActivity")
class GoodsSearchActivity : BaseMVIActivity() {

    private val binding: ActivityGoodsSearchBinding by lazy {
        ActivityGoodsSearchBinding.inflate(layoutInflater)
    }

    private lateinit var mViewModel: ShopViewModel

    private lateinit var searchContentView: View
    private lateinit var goodsAdapter: GoodsAdapter
    private var searchEmptyView: View? = null

    override fun generateViewModel() {
        mViewModel = ViewModelProvider(this)[ShopViewModel::class.java]
    }

    override fun getLayoutRootView(): View {
        return binding.root
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // 初始化内容布局和Adapter
        searchContentView = layoutInflater.inflate(R.layout.layout_search_content, binding.flSearchResult, false)
        val rv = searchContentView.findViewById<RecyclerView>(R.id.rvSearch)
        rv.layoutManager = GridLayoutManager(this, 2)
        goodsAdapter = GoodsAdapter(
            onItemClick = {
                ARouter.getInstance().build(Router.Ui.SHOP_DETAIL_ACTIVITY)
                    .withLong("shopId", it.id).navigation()
            }
        )
        rv.adapter = goodsAdapter

        showSearchEmpty() // 页面一进来就显示空布局
    }




    override fun initEvent() {

        // 1. 监听输入内容，控制叉号显示
        binding.etSearch.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                val keyword = s?.toString() ?: ""
                binding.ivClear.visibility = if (keyword.isNotEmpty()) View.VISIBLE else View.GONE
                doFuzzySearch(keyword)
            }

            override fun afterTextChanged(s: Editable?) {}
        })
        // 2. 叉号点击清空
        binding.ivClear.setOnClickListener {
            binding.etSearch.text?.clear()
            showSearchEmpty()
        }
        // 3. 取消按钮点击
        binding.tvCancel.setOnClickListener {
            binding.etSearch.clearFocus()
            binding.tvCancel.visibility = View.GONE
            // 可选：隐藏键盘
            val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
            imm.hideSoftInputFromWindow(binding.etSearch.windowToken, 0)
            // 可选：返回上一页
            finish()
        }
    }

    override fun handleState() {
        lifecycleScope.launch {
            mViewModel.state.collect { state ->
                when (state) {
                    is ShopState.QueryGoods -> {
                        val resultList = state.goods
                        if (resultList.isNotEmpty()) {
                            showSearchContent(resultList)
                        } else {
                            showSearchEmpty()
                        }
                    }

                    is ShopState.Error -> {
                        showSearchEmpty()
                    }

                    else -> {}
                }
            }
        }
    }

    private fun doFuzzySearch(keyword: String) {
        lifecycleScope.launch {
            val body = RequestSearchGoodsModel(keyword, 20, 0, 0, "", "", 1)
            mViewModel.intents.send(ShopIntent.QueryGoods(body))
        }
    }

    private fun showSearchContent(resultList: List<SearchGoodsModelItem>) {
        val fl = binding.flSearchResult
        fl.removeAllViews()
        goodsAdapter.submitList(resultList)
        fl.addView(searchContentView)
    }

    private fun showSearchEmpty() {
        val fl = binding.flSearchResult
        fl.removeAllViews()
        if (searchEmptyView == null) {
            searchEmptyView = layoutInflater.inflate(R.layout.layout_search_empty, fl, false)
        }
        fl.addView(searchEmptyView)
    }
}